package com.atguigu.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.client.PaymentFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.enums.OrderStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class OrderConsumer {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentFeignClient paymentFeignClient;

    //超时未支付 自动取消订单  手动签收
    @RabbitListener(queues = MqConst.CANCEL_ORDER_QUEUE)
    public void cancelOrder(Long orderId, Channel channel, Message message) throws Exception {
        if (orderId != null){
            //把订单改为已关闭
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            orderInfo.setOrderStatus(OrderStatus.CLOSED.name());
            orderInfo.setProcessStatus(ProcessStatus.CLOSED.name());
            orderInfoService.updateById(orderInfo);
            //把支付表单的状态改为已关闭
            rabbitTemplate.convertAndSend(MqConst.CLOSE_PAYMENT_EXCHANGE,MqConst.CLOSE_PAYMENT_ROUTE_KEY, orderInfo.getOutTradeNo());
            //如果支付宝有交易记录 把支付宝那边也改为关闭状态
            boolean flag = paymentFeignClient.queryAlipayTrade(orderId);
            if (flag) {
                paymentFeignClient.closeAlipayTrade(orderId);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //2.支付成功之后修改订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.PAY_ORDER_QUEUE, durable = "false"),
            exchange = @Exchange(value = MqConst.PAY_ORDER_EXCHANGE, durable = "false"),
            key = {MqConst.PAY_ORDER_ROUTE_KEY}))
    public void updateOrderAfterPaySuccess(Long orderId, Channel channel , Message message)throws Exception {
        if (orderId != null) {
            //修改订单状态
            OrderInfo orderInfo = orderInfoService.getOrder(orderId);
            //当订单状态为未支付时修改
            if (orderInfo != null&&orderInfo.getProcessStatus().equals(ProcessStatus.UNPAID.name())) {
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.PAID);
                //通知库存系统减库存
                orderInfoService.sendMsgToWareHouse(orderInfo);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //2.减库存成功后的代码
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.SUCCESS_DECREASE_STOCK_QUEUE, durable = "false"),
            exchange = @Exchange(value = MqConst.SUCCESS_DECREASE_STOCK_EXCHANGE, durable = "false"),
            key = {MqConst.SUCCESS_DECREASE_STOCK_ROUTE_KEY}))
    public void updateOrderAfterDecreseStock(String jsonData,Message message,Channel channel) throws Exception {
        if (!StringUtils.isEmpty(jsonData)) {
            //把json转换为map
            Map<String, Object> map = JSONObject.parseObject(jsonData);
            String orderId = (String) map.get("orderId");
            String status = (String) map.get("status");
            //如果仓库减库存成功就把订单状态改为等待发货
            OrderInfo orderInfo = orderInfoService.getOrder(Long.parseLong(orderId));
            if ("DEDUCTED".equals(status)){
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.WAITING_DELEVER);
            }else {
                orderInfoService.updateOrderStatus(orderInfo,ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }
}
